const {fork} = require("child_process");
const readline = require('readline');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true)

const bindEvent = ({ctrl = false, keyName, cb} = {}) => {
  process.stdin.on('keypress', (str, key) => {
    if (key.ctrl === ctrl && key.name === keyName) {
      cb()
    }
  })
};

bindEvent({
  ctrl: true, keyName: 'p', cb() {
    childProcess.kill()
    childProcess = createWorker()
  }
})


function createWorker(path) {
  const childProcess = fork(path);
  childProcess.on('message', message => {
    console.log(`main receive ${message}`)
  })

  childProcess.on('error', err => {
    console.error(err)
  })

  childProcess.send("")

  return childProcess;
}

let childProcess = createWorker(`${__dirname}/worker`);
